//
//  ModifyViewController.m
//  NOAHWM
//
//  Created by Ryan on 13-5-23.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "ForgetViewController.h"
#import "NSString+MobileNum.h"
#import "JSON.h"
#import "ResetPwdViewController.h"
#import "NYMemberCenterDataManager.h"

@interface ForgetViewController ()

@end

@implementation ForgetViewController

@synthesize phoneTextField,nextButton;
@synthesize kefuButton;

- (IBAction)nextButtonClicked:(id)sender
{
    [phoneTextField resignFirstResponder];
    NSString *validString = [self checkFieldValid];
    if(validString)
    {
        [[RYHUDManager sharedManager] showWithMessage:validString customView:nil hideDelay:2.f];
    }
    else
    {
        NSString *suburl = [NSString stringWithFormat:kBeginFindPwdUrl,@"jsonp",phoneTextField.text];
        suburl = [suburl stringByAppendingString:@"app000003"];
        NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:nil];
        [[RYHUDManager sharedManager] startedNetWorkActivityWithText:@"密码获取中..."];
    }
}

- (NSString *)checkFieldValid
{
    //姓名长度1-20
    //手机号长度11-11 手机号验证
    if(phoneTextField.text.length < 1)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000001E"],@"手机号"];
    else if(phoneTextField.text.length > 11)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000002E"],@"手机号"];
    else if(![NSString isMobileNumber:phoneTextField.text])
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000003E"],@"手机号"];
    return nil;
}

- (void)enableNextButton
{
    self.nextButton.enabled = YES;
}
#pragma mark - BaseViewController methods
- (void)leftItemTapped
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIViewController methods

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setNaviTitle:@"找回密码"];
    [self setLeftNaviItemWithTitle:nil imageName:@"Icon_Back"];
    [self setRightNaviItemWithTitle:nil imageName:nil];
    [self addSwipePopGesture];
    
    [self.kefuButton setTitle:[NSString stringWithFormat:@"客服热线：%@",[NYMemberCenterDataManager sharedManager].loginMember.custom_service_phone] forState:UIControlStateNormal];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.isViewLoaded && !self.view.window)
    {
        [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
        self.view = nil;
        self.phoneTextField = nil;
        self.nextButton = nil;
        self.kefuButton = nil;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    self.phoneTextField = nil;
    self.nextButton = nil;
    self.kefuButton = nil;
}

- (void)dealloc
{
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    [kefuButton release];
    [phoneTextField release];
    [nextButton release];
    [super dealloc];
}

#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    NSDictionary *dict = [str JSONValue];
    if([[dict objectForKey:@"result"] isEqualToString:@"1"])
    {
        //获取动态密码成功之后的30秒内设置nextButton不可点击，同时进入密码修改页面
        self.nextButton.enabled = NO;
        [self performSelector:@selector(enableNextButton) withObject:nil afterDelay:30.f];
        ResetPwdViewController *rpvc = [[ResetPwdViewController alloc] init];
        rpvc.dynPwd = [dict objectForKey:@"verifycode"];
        rpvc.phoneNum = self.phoneTextField.text;
        [self.navigationController pushViewController:rpvc animated:YES];
        [rpvc release];
    }
    [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
}
- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
}

#pragma mark - UI控制，by Charles
@synthesize phoneCallAs;

- (UIActionSheet *)phoneCallAs
{
    if(nil == phoneCallAs)
    {
        phoneCallAs = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"咨询客服", nil];
    }
    return phoneCallAs;
}

//取消键盘
- (void)resignAllField
{
    [self.phoneTextField resignFirstResponder];
}

- (IBAction)hideKeyboardButtonClick:(id)sender
{
    [self resignAllField];
}

- (IBAction)kefuButtonClick:(id)sender
{
    [self resignAllField];
    [self.phoneCallAs showInView:self.view];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if(textField == self.phoneTextField)
    {
        [self.phoneTextField resignFirstResponder];
        [self nextButtonClicked:nil];
    }
    return YES;
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 0)
    {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",[NYMemberCenterDataManager sharedManager].loginMember.custom_service_phone]]];
    }
}
@end
